package io.jee.medusa.remote;

import io.jee.runshan.domain.remote.WeixinRequest;
import io.jee.runshan.domain.remote.WeixinResponse;
import io.jee.runshan.utils.JsonUtil;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class RemoteConnector {
	
	public static WeixinResponse post(String actionUrl, WeixinRequest request) {
		WeixinResponse response = null;
		try {
	        String json = send(actionUrl, request, "POST");
	        response = JsonUtil.jsonToBean(json, WeixinResponse.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
        return response;
	}
	
	public static WeixinResponse get(String actionUrl, WeixinRequest request) {
		WeixinResponse response = null;
		try {
	        String json = send(actionUrl, request, "GET");
	        response = JsonUtil.jsonToBean(json, WeixinResponse.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
        return response;
	}
	
	
	public static String send (String actionUrl, WeixinRequest request, String method) {
		String json = "";
		try {
			if (request != null) {
				json = JsonUtil.beanToJson(request);
			}
			URL url = new URL(actionUrl);
	        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
	        httpConn.setRequestProperty("Content-Length", String.valueOf(json.getBytes().length));
	        httpConn.setRequestProperty("Content-Type", "text/json; charset=UTF-8");
	        httpConn.setRequestMethod(method);
	        httpConn.setDoOutput(true);
	        httpConn.setDoInput(true);
	        OutputStream out = httpConn.getOutputStream();
	        out.write(json.getBytes());
	        out.close();
	        json = new String(readInputStream(httpConn.getInputStream()), "UTF-8");
		} catch (Exception e) {
			json = null;
			e.printStackTrace();
		}
        return json;
	}
	
    /**
     * 从输入流中读取数据
     * @param inStream
     * @return
     * @throws Exception
     */
    private static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len = inStream.read(buffer)) !=-1 ){
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;
    }
}
